﻿using System.Linq;
using System.Net.Sockets;

namespace Middleware
{
    public class ClientRequestHandler : RequestHandler
    {
        public ClientRequestHandler(IOR ior)
            : base(ior.IP as string, (int)ior.Port) {
        }

        public byte[] Send(byte[] data) {
            return Send(data, false);
        }

        public byte[] Send(byte[] data, bool waitResponse) {
            using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
                socket.Connect(_endpoitAddress);
                socket.Send(data);
                if (waitResponse) {
                    byte[] result = new byte[RequestHandler.MAX_BYTES_PER_MESSAGE];
                    int bytes = socket.Receive(result);
                    return result.Take(bytes).ToArray();
                }
                return null;
            }
        }
    }
}
